
import axios from 'axios';
import { QueryString } from '../utils/tools';
import { LogoutBase } from './base';

const isContentTypeJson = function (data) {
    return (data['Content-Type'] || data['content-type'] || '').indexOf('application/json') > -1;
}
const getCodePrexfix = function (url = '') {
    if (url.indexOf('boss-api.') > -1) return 'erp.code.';
    if (url.indexOf('fbb-api.') > -1) return 'fbb.code.';
    if (url.indexOf('ucenter.') > -1) return 'ucenter.code.';
    return 'code.'
}
const Instance = axios.create({
    method: 'POST',
    headers: {
        // "Content-Type": "application/x-www-form-urlencoded",
        // "X-Requested-With": "XMLHttpRequest"
    },
    timeout: 300000,
    withCredentials: true,
    responseType: 'json',
    paramsSerializer: function (params) {
        params = { contextId: global.SYSID || '', lang: global.LANG, ...params };
        if (!params.contextId) delete params.contextId;
        return QueryString.stringify(params);
    },
    transformRequest: function (data, headers) {
        data = { contextId: global.SYSID, ...data };
        return isContentTypeJson(headers) ? JSON.stringify(data) : QueryString.stringify(data);
    },
    validateStatus: function () {
        return true;
    },
});
Instance.interceptors.request.use(function (request) {
    const token = global.AUTH_TOKEN;
    request.params = request.params || {};
    if (token) request.headers.common['Authorization'] = `Bearer ${token}`;
    request.baseURL = request.baseURL || process.env.VUE_APP_APIURL_BASE;
    return request;
});
Instance.interceptors.response.use(function (response) {
    let data = response.data || {},
        status = response.status,
        code = status;

    // console.log(status, code , data)
    
    if (isContentTypeJson(response.headers)) {
        data = typeof data === 'string' ? JSON.parse(data) : data;
        code = data.code;
        data.langCode = getCodePrexfix(response.config.baseURL) + code;
        // console.log(data)
    }
    if (status == 200 && (code == 200 || code == 206 || code == 0)) {
        // 同步本地数据
        // if (process.env.VUE_APP_APIURL_LOCAL_SYNC && !data.reject)  _SaveResToLocal(response.config.url, response);
        const disposition = response.headers['content-disposition'] || response.headers['Content-Disposition'];
        if (disposition) {
            try {
                data.fileName = decodeURIComponent(disposition.split(';')[1].split('=')[1]);
            } catch (err) {
                // console.log(err)
            }
        }
        return data;
    }
    if (status == 401 || code == 401) LogoutBase();

    // 导出文件时的操作
    if (status == 200 && code == undefined) {
        return Promise.reject(data);
    }
    return Promise.reject({
        ...data,
        originResponse: response
    });
}, function (error) {
    const INFO = "网络异常，请稍后重试";
    const URL = `${error.config.baseURL}${error.config.url}`;
    let message = `${INFO}. url:${URL}`;
    // 线上环境不展示URL
    if (process.env.NODE_ENV == "production") {
        message = INFO;
    }
    return Promise.reject({
        // message: `Network Error. url:${error.config.baseURL}${error.config.url}`
        message: message
    })
});
export default Instance;

// const sourceTokens = {},
//     CancelToken = axios.CancelToken,
//     handleTokenMap = function(url) {
//         let source = sourceTokens[url];
//         if (source) source.cancel("Operation canceled by the user!");
//         source = CancelToken.source();
//         sourceTokens[url] = source;
//         return source.token;
//     };
// const GeneratorList = {
//     queueIndex:0,
//     queue: [],
//     push(gen) {
//         GeneratorList.queue.push(gen);
//         GeneratorList.start();
//     },
//     start() {
//         const queueIndex=GeneratorList.queueIndex;
//         if(queueIndex>3||queueIndex<0||GeneratorList.queue.length<=0) return;
//         GeneratorList.queueIndex++;
//         const gen =  GeneratorList.queue.shift();
//         if(!gen){
//             GeneratorList.queueIndex--;
//             GeneratorList.start();
//             return
//         }
//         gen.next().value.then(function (data) {
//             gen.next(data);
//             GeneratorList.queueIndex--;
//             GeneratorList.start();
//         }).catch(function (data) {
//             console.log(data)
//             data.statusCode=-1;
//             gen.next(data);
//             GeneratorList.queueIndex--;
//             GeneratorList.start();
//         })
//     }
// };
// const  generatorPromise=function(url,method,data,config){
//     return new Promise(function(resolve, reject) {
//         const gen = (function*() {
//             const result = yield Instance[method](url,data,config);
//             console.log(result);
//             if(result.statusCode==-1){
//                 reject(result)
//             }else{
//                 resolve(result)
//             }
//         })();
//         GeneratorList.push(gen);
//     });
// }
// export default {
//     async get(url, config) {
//         return generatorPromise(url,'get',{ cancelToken: handleTokenMap(url),...config})
//         // return Instance.get(url, { cancelToken: handleTokenMap(url), ...config});
//     },
//     async post(url, data, config) {
//         return generatorPromise(url,'post',data,{ cancelToken: handleTokenMap(url),...config})
//         // return Instance.post(url, data, { cancelToken: handleTokenMap(url), ...config});
//     }
// };